package com.wngbms.feigndemo.controller;

import com.wngbms.feigndemo.api.LoginService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.UUID;

@Slf4j
@RestController
public class LoginController implements LoginService {

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Override
    public LoginResp login(@RequestBody LoginReq loginReq) {

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            log.info("header {}:{}", s, header);
        }
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String s = parameterNames.nextElement();
            String parameter = request.getParameter(s);
            log.info("param {}:{}", s, parameter);
        }

        response.addCookie(new Cookie("sessionId", UUID.randomUUID().toString()));
        response.addCookie(new Cookie("token", UUID.randomUUID().toString()));
        return LoginResp.success();
    }

    @Data
    public static class LoginReq {
        String username;
        String password;
    }

    @Data
    public static class LoginResp {
        Integer code;
        String message;

        public static LoginResp success() {
            LoginResp loginResp = new LoginResp();
            loginResp.setCode(0);
            loginResp.setMessage("success");
            return loginResp;
        }
    }
}
